package com.oocl.jdbc_homework.con_pool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.oocl.jdbc_homework.util.DBUtil;

public class ConPool {
	private List<Connection> freeCons = new LinkedList<>();
	private List<Connection> buzyCons = new LinkedList<>();
	private int max = 10;
	private int min = 2;
	private int current = 0;
	private String className;
	private String url;// 这就是协议
	private String username;
	private String psd;
	
	

	public static class ConPoolBuilder{
		private static ConPool conPool;
		public static ConPool getPool(){
			conPool = new ConPool();
			return conPool;
		}
		public static ConPool setMax(int max){
			conPool.setMax(max);
			return conPool;
		}
		/**
		 * TODO
		 */
	}
	
	public void setMax(int max) {
		this.max = max;
	}

	public void setMin(int min) {
		this.min = min;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPsd(String psd) {
		this.psd = psd;
	}

	private ConPool() {
		while (this.min > this.current) {
			this.freeCons.add(this.createCon());
		}
	}
	
	

	
	/**
	 * 获取数据库连接
	 * 
	 * @return 数据库连接
	 */
	public Connection getCon() {
		Connection myCon = this.getFreeCon();
		if (myCon != null)
			return myCon;
		return this.getNewCon();
	}

	/**
	 * 设置连接为空闲状态
	 * 
	 * @param con
	 *            连接
	 */
	public void setFree(Connection con) {
		this.buzyCons.remove(con);
		this.freeCons.add(con);
	}

	/**
	 * 
	 * @return 返回当前连接池的连接状态
	 */
	public String toString() {
		return "当前连接数：" + this.current + "，空闲连接数：" + this.freeCons.size()
				+ "，繁忙连接数：" + this.buzyCons.size();
	}

	// ========================================================================================

	private Connection getNewCon() {

		if (this.current >= this.max)
			return null;
		Connection myCon = this.createCon();
		assert myCon != null;
		this.buzyCons.add(myCon);
		return myCon;
	}

	private Connection createCon() {
		try {
			Connection connection = DBUtil.createConnection();
			this.current++;
			return connection;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private Connection getFreeCon() {
		if (freeCons.size() > 0) {
			Connection con = freeCons.remove(0);
			this.buzyCons.add(con);
			return con;
		}
		return null;
	}
}
